@using DaoHang.Services
@using DaoHang.Models
@inject IDataExportService DataExportService
@inject IJSRuntime JSRuntime

<div class="card">
    <div class="card-header">
        <h5 class="mb-0">
            <i class="bi bi-download me-2"></i>数据管理
        </h5>
    </div>
    <div class="card-body">
        <div class="row g-4">
            <!-- 数据导出 -->
            <div class="col-md-6">
                <div class="card border-primary h-100">
                    <div class="card-header bg-primary text-white">
                        <h6 class="mb-0"><i class="bi bi-box-arrow-down me-2"></i>数据导出</h6>
                    </div>
                    <div class="card-body">
                        <p class="text-muted mb-4">
                            导出网站数据备份，包括网站、分类和设置信息。导出的JSON文件可用于恢复或迁移数据。
                        </p>

                        <div class="d-grid gap-2">
                            <button class="btn btn-outline-primary" @onclick="ExportAllData" 
                                    disabled="@isExporting">
                                @if (isExporting)
                                {
                                    <span class="spinner-border spinner-border-sm me-2"></span>
                                    <span>导出中...</span>
                                }
                                else
                                {
                                    <i class="bi bi-download me-2"></i>
                                    <span>导出所有数据</span>
                                }
                            </button>
                            
                            <button class="btn btn-outline-primary" @onclick="ExportWebsitesOnly" 
                                    disabled="@isExporting">
                                <i class="bi bi-globe me-2"></i>
                                <span>仅导出网站数据</span>
                            </button>
                            
                            <button class="btn btn-outline-primary" @onclick="ExportCategoriesOnly" 
                                    disabled="@isExporting">
                                <i class="bi bi-grid-3x3-gap me-2"></i>
                                <span>仅导出分类数据</span>
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 数据导入 -->
            <div class="col-md-6">
                <div class="card border-success h-100">
                    <div class="card-header bg-success text-white">
                        <h6 class="mb-0"><i class="bi bi-box-arrow-up me-2"></i>数据导入</h6>
                    </div>
                    <div class="card-body">
                        <p class="text-muted mb-4">
                            从备份文件恢复数据。请确保导入的JSON文件格式正确，以避免数据损坏。
                        </p>

                        <div class="mb-3">
                            <label for="importFile" class="form-label">选择导入文件（JSON格式）</label>
                            <InputFile id="importFile" OnChange="OnFileSelected" class="form-control" accept=".json" />
                        </div>

                        <div class="form-check mb-3">
                            <input class="form-check-input" type="checkbox" id="overwriteExisting" 
                                   @bind="overwriteExisting" />
                            <label class="form-check-label" for="overwriteExisting">
                                覆盖现有数据（谨慎选择）
                            </label>
                        </div>

                        <div class="d-grid">
                            <button class="btn btn-success" @onclick="ImportData" 
                                    disabled="@(isImporting || selectedFile == null)">
                                @if (isImporting)
                                {
                                    <span class="spinner-border spinner-border-sm me-2"></span>
                                    <span>导入中...</span>
                                }
                                else
                                {
                                    <i class="bi bi-box-arrow-in-down me-2"></i>
                                    <span>导入数据</span>
                                }
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

@code {
    /// <summary>
    /// 是否正在导出数据
    /// </summary>
    private bool isExporting = false;

    /// <summary>
    /// 是否正在导入数据
    /// </summary>
    private bool isImporting = false;

    /// <summary>
    /// 选择的导入文件
    /// </summary>
    private IBrowserFile? selectedFile;

    /// <summary>
    /// 是否覆盖现有数据
    /// </summary>
    private bool overwriteExisting = false;

    /// <summary>
    /// 导出所有数据
    /// </summary>
    private async Task ExportAllData()
    {
        isExporting = true;
        try
        {
            var jsonData = await DataExportService.ExportAllDataAsync();
            await DownloadFile(jsonData, "daohang_all_data.json");
        }
        catch (Exception)
        {
            await JSRuntime.InvokeVoidAsync("alert", "导出数据失败，请重试");
        }
        finally
        {
            isExporting = false;
            StateHasChanged();
        }
    }

    /// <summary>
    /// 仅导出网站数据
    /// </summary>
    private async Task ExportWebsitesOnly()
    {
        try
        {
            var websites = await DataExportService.ExportWebsitesAsync();
            // 转换为JSON
            var jsonData = System.Text.Json.JsonSerializer.Serialize(websites, new System.Text.Json.JsonSerializerOptions { 
                WriteIndented = true 
            });
            await DownloadFile(jsonData, "daohang_websites.json");
        }
        catch (Exception)
        {
            await JSRuntime.InvokeVoidAsync("alert", "导出网站数据失败，请重试");
        }
    }

    /// <summary>
    /// 仅导出分类数据
    /// </summary>
    private async Task ExportCategoriesOnly()
    {
        try
        {
            var categories = await DataExportService.ExportCategoriesAsync();
            // 转换为JSON
            var jsonData = System.Text.Json.JsonSerializer.Serialize(categories, new System.Text.Json.JsonSerializerOptions { 
                WriteIndented = true 
            });
            await DownloadFile(jsonData, "daohang_categories.json");
        }
        catch (Exception)
        {
            await JSRuntime.InvokeVoidAsync("alert", "导出分类数据失败，请重试");
        }
    }

    /// <summary>
    /// 处理文件选择事件
    /// </summary>
    private void OnFileSelected(InputFileChangeEventArgs e)
    {
        selectedFile = e.File;
    }

    /// <summary>
    /// 导入数据
    /// </summary>
    private async Task ImportData()
    {
        if (selectedFile == null)
        {
            await JSRuntime.InvokeVoidAsync("alert", "请先选择导入文件");
            return;
        }

        // 检查文件类型
        if (!selectedFile.ContentType.Contains("json") && !selectedFile.Name.EndsWith(".json"))
        {
            await JSRuntime.InvokeVoidAsync("alert", "请选择JSON格式的文件");
            return;
        }

        // 确认导入
        bool confirmed = await JSRuntime.InvokeAsync<bool>("confirm", 
            overwriteExisting 
                ? "导入将覆盖现有数据，此操作不可恢复！确定要继续吗？" 
                : "确定要导入数据吗？");
        
        if (!confirmed)
        {
            return;
        }

        isImporting = true;
        try
        {
            // 读取文件内容
            using var stream = selectedFile.OpenReadStream(maxAllowedSize: 10 * 1024 * 1024); // 限制10MB
            using var reader = new StreamReader(stream);
            var jsonContent = await reader.ReadToEndAsync();

            // 导入数据
            var result = await DataExportService.ImportDataFromJsonAsync(jsonContent, overwriteExisting);
            
            // 显示导入结果
            if (result.success)
            {
                await JSRuntime.InvokeVoidAsync("alert", 
                    $"导入成功！\n{result.message}\n共导入 {result.importedCount} 项数据。");
            }
            else
            {
                await JSRuntime.InvokeVoidAsync("alert", $"导入失败：{result.message}");
            }
            
            // 重置文件选择
            selectedFile = null;
        }
        catch (Exception ex)
        {
            await JSRuntime.InvokeVoidAsync("alert", $"导入数据失败：{ex.Message}");
        }
        finally
        {
            isImporting = false;
            StateHasChanged();
        }
    }

    /// <summary>
    /// 下载文件到浏览器
    /// </summary>
    private async Task DownloadFile(string content, string filename)
    {
        // 使用JS将内容保存为文件
        var escapedContent = content.Replace("\\", "\\\\").Replace("'", "\\'").Replace("\r", "\\r").Replace("\n", "\\n");
        var escapedFilename = filename.Replace("\\", "\\\\").Replace("'", "\\'");
        
        string jsCode = @"
            (function() {
                const blob = new Blob(['" + escapedContent + @"'], { type: 'application/json' });
                const link = document.createElement('a');
                link.download = '" + escapedFilename + @"';
                link.href = URL.createObjectURL(blob);
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
            })();
        ";
        
        await JSRuntime.InvokeVoidAsync("eval", jsCode);
    }
} 